package com.fsds.crem.web.controller;

import java.util.Hashtable;

import javax.annotation.Resource;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fsds.crem.core.util.ResourceUtils;
import com.fsds.crem.web.entity.Users;
import com.fsds.crem.web.service.UsersService;


@Controller
@RequestMapping(value = "/login")
public class LoginController {

	private Logger logger = Logger.getLogger(LoginController.class);
	
	@Resource
	private UsersService usersService;

	/**
	 * 登录时用户名和密码验证
	 * 
	 * @param users
	 * @return
	 */
	@RequestMapping(value = "/checkUser")
	@ResponseBody
	public String checkUser(HttpServletRequest request,Users users) {

		JSONObject result = new JSONObject();
		
		try {
			
			if(usersService.findUsersIsExist(users)){
				
//				boolean flag = ldap_auth_ad(users.getUserName(), users.getPassword());
				
				boolean flag = true;
				
				if(flag){
					
					result.put("result", "success");
					// 将用户信息存储到session中 
					request.getSession().setAttribute("user", users);
				}
			}
			else{
				
				result.put("result", "fail");
			}
			
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			e.printStackTrace();
			result.put("result", "error");
		} 

		return result.toString();
	}

	/**
	 * 登录成功
	 * 
	 * @param request
	 * @param users
	 * @return
	 */
	@RequestMapping(value = "/loginSuccess")
	public String loginSuccess(HttpServletRequest request) {

		return "main";
	}
	
	/**
	 * 注销，登出
	 * 
	 * @param request
	 * @param users
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request,Users users) {

		request.getSession().removeAttribute("user");
		
		return "login";
	}
	
	
	/**
	 * LDAP认证
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public static boolean ldap_auth_ad(String account, String password) {		
		Hashtable<String, String> env = new Hashtable<String, String>();
		LdapContext ctx = null;
		
		env.put("java.naming.factory.initial", ResourceUtils.getConfigByName("initial_context_factory"));
		env.put("java.naming.security.authentication", ResourceUtils.getConfigByName("security_authentication"));
		env.put("java.naming.provider.url", ResourceUtils.getConfigByName("provider_url"));
		env.put("java.naming.security.principal", account + "@smegold.com");
		env.put("java.naming.security.credentials", password);
		
		try {
			ctx = new InitialLdapContext(env, null);
			
		} catch (javax.naming.AuthenticationException e) {
			e.printStackTrace();
			return false;
		} catch (javax.naming.CommunicationException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (ctx != null) {
				try {
					ctx.close();
				} catch (NamingException e) {
					return false;
				}
			}
		}
		return true;
	}
	
	
	/** 
	 * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址, 
	 * 
	 * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？ 
	 * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 
	 * 
	 * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130, 
	 * 192.168.1.100 
	 * 
	 * 用户真实IP为： 192.168.1.110 
	 * 
	 * @param request 
	 * @return ip
	 */
	public String getIpAddress(HttpServletRequest request) {
		
		String ip = request.getHeader("x-forwarded-for");
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			
			ip = request.getHeader("Proxy-Client-IP");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			
			ip = request.getRemoteAddr();
		}
		
		return ip; 
	}
	
}